var config = require('/utils/config');
var db = require('/utils/db');
App({  
  queryUser:function (openId) {
    var util = require('/utils/util');
    var that = this;    
    var options = {
      url: config.clubApi.wxUser,
      data: {
        openId: openId
      }
    };
    util.request(options, function (res) {
      if (res.data.data) {
        this.setUserInfo(res.data.data);
      }else {
        wx.setStorageSync('user', null);
      }
    });
  },
  getUserInfo:function(cb) {
    var that = this;
    if (this.globalData.userInfo!=null) {
      typeof cb == "function" && cb(this.globalData.userInfo)
    }else {
      //调用登录接口
      wx.login({
        success: function (resLogin) {
          let code = resLogin.code;
          wx.getUserInfo({
            success: function (res) {
              that.globalData.userInfo = res.userInfo;
              db.putOpenid(code, (resOpen, err) => {
                if (resOpen.data.data.userId) {
                  this.setUserInfo(resOpen.data.data);
                }else {
                  let openId = resOpen.data.data.openid;
                  that.queryUser(openId);
                }
              });
              typeof cb == "function" && cb(that.globalData.userInfo)
            }
          })
        }
      })
    }
  },
  setUserInfo(obj) {
    var that = this;
    that.globalData.userInfo = {};
    that.globalData.userInfo.userId = obj.userId;
    that.globalData.userInfo.userName = obj.userName;
    that.globalData.userInfo.avatar = obj.avatar;
    that.globalData.userInfo.phonenumber = obj.phonenumber;
    wx.setStorageSync('user', that.globalData.userInfo);
  },
  globalData:{
    userInfo:null
  }
})